package com.hundsun.epay.autosimu.api;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.hundsun.epay.autosimu.config.Configuration;
import com.hundsun.epay.autosimu.config.PayCorporation;
import com.hundsun.epay.autosimu.exception.InvalidConfigurationException;

public class AutoSimuGenerator {
	/** This configuration */
	private Configuration configuration;
	
	/** This generated java files */
	private List<GeneratedJavaFile> generatedJavaFiles;

	public AutoSimuGenerator(Configuration configuration) throws InvalidConfigurationException {
		if(configuration == null){
			throw new IllegalArgumentException("Configuration is required");
		}
		this.configuration = configuration;
		this.generatedJavaFiles = new ArrayList<GeneratedJavaFile>();
		this.configuration.validate();
	}
	
	public void generate(){
		generate(null, null, null, true);
	}
	
	public void generate(Set<String> payCorpIds){
		generate(payCorpIds, null, null, true);
	}
	
	public void generate(Set<String> payCorpIds, Set<String> channelIds){
		generate(payCorpIds, channelIds, null, true);
	}
	
	public void generate(Set<String> payCorpIds, Set<String> channelIds, Set<String> tradeIds){
		generate(payCorpIds, channelIds, tradeIds, true);
	}
	
	public void generate(Set<String> payCorpIds, Set<String> channelIds, Set<String> tradeIds, boolean writeFiles){
		List<String> wrannings = new ArrayList<String>();
		//清空列表
		this.generatedJavaFiles.clear();
		
		//计算要执行的payCorp
		List<PayCorporation> payCorpToRun;
		if(payCorpIds == null || payCorpIds.isEmpty()){
			payCorpToRun = this.configuration.getCorps();
		}else{
			payCorpToRun = new ArrayList<PayCorporation>();
			for (PayCorporation payCorporation : this.configuration.getCorps()) {
				if(payCorpIds.contains(payCorporation.getId())){
					payCorpToRun.add(payCorporation);
				}
			}
		}
		
		//执行内省
		for (PayCorporation payCorporation : payCorpToRun) {
			payCorporation.introspectChannel(channelIds, tradeIds);
		}
		
		//执行生成
		for (PayCorporation payCorporation : payCorpToRun) {
			payCorporation.generateFiles(generatedJavaFiles, wrannings);
		}
	}
}
